package com.simple.crawler.connect;

import com.simple.crawler.connect.ext.StringResponseConverter;
import com.simple.crawler.constant.ExceptionCode;
import com.simple.crawler.core.CrawlerContext;
import com.simple.crawler.exception.CrawlerRuntimeException;

import java.io.InputStream;

/**
 * @ClassName Response
 * @Author Administrator
 * @Desc TODO
 * @CreateTime 2019/8/3 22:00
 */
public abstract class Response {

    protected int responseCode;

    protected String charSet;

    protected Object content;

    public int getResponseCode() {
        return responseCode;
    }

    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    public String getCharSet() {
        return charSet;
    }

    public void setCharSet(String charSet) {
        this.charSet = charSet;
    }

    public Object getContent() {
        return content;
    }

    public void setContent(Object content) {
        this.content = content;
    }

    public Response doConvert(Class<? extends ResponseConverter> converterType) throws Exception {
        if (content == null) {
            throw new CrawlerRuntimeException(ExceptionCode.CONVERT_ERROR);
        }
        ResponseConverter converter = CrawlerContext.getObj(converterType);
        if (converter instanceof StringResponseConverter) {
            ((StringResponseConverter) converter).setCharSet(charSet);
        }
        this.content = converter.doConvert((InputStream) content);
        return this;
    }

    public boolean isSuccess() {
        return true;
    }

    @Override
    public String toString() {
        return "Response{" +
                "responseCode=" + responseCode +
                ", charSet=" + charSet +
                ", content=" + content +
                '}';
    }
}
